package org.springblade.modules.repair.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.log.exception.ServiceException;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 获取电梯年检时间工具类
 * @author Jackey
 * @date 2021年10月23日 10:54 上午
 */
@Component
@Slf4j
public class ElevatorAuditUtil {


    /**
     * 批量获取电梯年检时间
     *
     * @param privateNumList
     * @return
     * @throws Exception
     */
    public VCodeResult vCodeByPrivateNumList(List<String> privateNumList) {

        VCodeResult vCodeResult = new VCodeResult();

		log.info("========= 开始同步电梯年检时间 =========");
        if (privateNumList.size() > 0) {

            int failCount = 0;

            for (String privateNum : privateNumList) {
                String result = this.vCodeByPrivateNum(privateNum);
                if (result.equals("false")) {
                    failCount++;
                    vCodeResult.getFailPrivateNumList().add(privateNum);
                } else {
                    Map<String, String> successResultMap = new HashMap<>(2);
                    successResultMap.put("privateNum", privateNum);
                    successResultMap.put("yearCheckTime", result);
                    vCodeResult.getSuccessResultList().add(successResultMap);
                }
            }

            vCodeResult.setFailCount(failCount);
            vCodeResult.setTotal(privateNumList.size());
            vCodeResult.setSuccessCount(vCodeResult.getTotal() - vCodeResult.getFailCount());
        }

		log.info("========= 结束同步电梯年检时间 total: {}, success: {}, error: {} =========",vCodeResult.getTotal(), vCodeResult.getSuccessCount(), vCodeResult.getFailCount());
        return vCodeResult;
    }

    /**
     * 最大尝试3次调用,返回年检时间字符串
     *
     * @param privateNum
     * @return
     * @throws Exception
     */
    public String vCodeByPrivateNum(String privateNum) {
        int i = 0;
        String checkString = null;
        do {
        	try {
				checkString = this.vCodeCheck(privateNum);
			} catch (Exception e) {
				checkString = "false";
			}
            i++;
        }
        while (i < 3 && checkString.equals("false"));
        return checkString;
    }

    /**
     * 返回处理好的下一次年检时间字符串
     *
     * @param privateNum
     * @return
     * @throws Exception
     */
    private String vCodeCheck(String privateNum) throws Exception {
        String base64AuthCode = this.getBase64AuthCode();
        String authCode = this.getAuthCode(base64AuthCode);
        return this.getYearCheckTime(authCode, privateNum);
    }

    /**
     * 获取网办验证码(base64)
     *
     * @return 图片base64编码
     * @throws Exception
     */
    private String getBase64AuthCode() throws Exception {
        SortedMap<String, String> dataMap = new TreeMap<String, String>() {
            private static final long serialVersionUID = 1L;

            {
                put("service", "App.Common.GetCAPTCHA");
            }
        };
        String json = JSONUtil.toJsonStr(dataMap);
        String body = HttpRequest.post("https://php.zsjcy.com/api/php/")
                .body(json).execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(body);
        if (jsonObject.isNull("ret") || Integer.parseInt(jsonObject.get("ret").toString()) != 200) {
            throw new ServiceException("获取验证码失败");
        }
        return JSONUtil.parseObj(jsonObject.get("data")).get("base64Data").toString();
    }

    /**
     * base64图片转文字
     *
     * @param base64ImageCode
     * @return
     * @throws Exception
     */
    private String getAuthCode(String base64ImageCode) throws Exception {
        SortedMap<String, String> dataMap = new TreeMap<String, String>() {
            private static final long serialVersionUID = 1L;

            {
                put("username", "taiji");
                put("password", "taiji123");
                put("image", base64ImageCode);
            }
        };
        String json = JSONUtil.toJsonStr(dataMap);
        String body = HttpRequest.post("http://api.ttshitu.com/predict")
                .body(json).execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(body);
        if (jsonObject.isNull("success") || !Boolean.parseBoolean(jsonObject.get("success").toString())) {
            throw new ServiceException("base64图片解析失败");
        }
        return JSONUtil.parseObj(jsonObject.get("data")).get("result").toString();

    }

    /**
     * 获取下次年检时间
     *
     * @param authCodeString
     * @param privateNum
     * @return
     * @throws Exception
     */
    private String getYearCheckTime(String authCodeString, String privateNum) throws Exception {
        SortedMap<String, String> dataMap = new TreeMap<String, String>() {
            private static final long serialVersionUID = 1L;

            {
                put("service", "App.Report.QueryReportStepList");
                put("EQUCLANAME", "全部");
                put("EQULOGCODE", privateNum);
                put("CAPTCHA", authCodeString);
            }
        };
        String json = JSONUtil.toJsonStr(dataMap);
        String body = HttpRequest.post("https://php.zsjcy.com/api/php/")
                .body(json).execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(body);
        if (jsonObject.isNull("ret") || Integer.parseInt(jsonObject.get("ret").toString()) != 200) {
            return "false";
        }
        return JSONUtil.parseObj(JSONUtil.parseArray(JSONUtil.parseObj(jsonObject.get("data")).get("reportStepList")).get(0)).get("NINSPDATE").toString();
    }


    public static void main(String[] args) throws Exception {
        ElevatorAuditUtil elevatorAuditUtil = new ElevatorAuditUtil();
        VCodeResult vCodeResult = elevatorAuditUtil.vCodeByPrivateNumList(Arrays.asList("31104420002012060041", "31104420002013040004", "31104420002010060080"));
        System.out.println("====end====");
    }
}
